Page({
  data: {
    // 音乐菜单结构
    musicMenus: [],
    
    // 当前播放状态
    currentPlaying: null,
    isPlaying: false,
    currentTime: 0,
    totalTime: 0,
    
    // 播放模式
    playMode: 'sequence', // sequence, single, random
    
    // 用户自定义歌单
    customPlaylists: [],
    
    // 加载状态
    loading: false
  },

  onLoad() {
    // 检查是否是第一次进入音乐页面
    this.checkFirstVisit();
    
    // 加载用户自定义歌单
    // this.loadCustomPlaylists();
    // 从服务器加载音乐文件
    // this.loadMusicFiles();
    
    // 初始化背景音频管理器
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    
    // 监听背景音频播放事件
    this.backgroundAudioManager.onPlay(() => {
      console.log('背景音频开始播放');
      this.setData({ isPlaying: true });
    });
    
    // 监听背景音频暂停事件
    this.backgroundAudioManager.onPause(() => {
      console.log('背景音频暂停');
      this.setData({ isPlaying: false });
    });
    
    // 监听背景音频停止事件
    this.backgroundAudioManager.onStop(() => {
      console.log('背景音频停止');
      this.setData({ 
        isPlaying: false,
        currentPlaying: null
      });
    });
    
    // 监听背景音频自然结束事件
    this.backgroundAudioManager.onEnded(() => {
      console.log('背景音频自然结束');
      this.setData({ isPlaying: false });
      // 自动播放下一首
      this.nextSong();
    });
    
    // 监听背景音频播放进度更新事件
    this.backgroundAudioManager.onTimeUpdate(() => {
      this.setData({
        currentTime: this.backgroundAudioManager.currentTime,
        totalTime: this.backgroundAudioManager.duration
      });
    });
    
    // 监听背景音频播放错误事件
    this.backgroundAudioManager.onError((res) => {
      console.error('背景音频播放错误', res);
      wx.showToast({
        title: '播放出错',
        icon: 'none'
      });
    });
  },

  // 检查是否是第一次进入音乐页面
  checkFirstVisit() {
    try {
      const hasVisited = wx.getStorageSync('hasVisitedMusicPage');
      if (!hasVisited) {
        // 第一次进入，显示蓝牙连接提示
        this.showBluetoothTip();
        // 标记已访问
        wx.setStorageSync('hasVisitedMusicPage', true);
      }
    } catch (error) {
      console.error('检查访问状态失败:', error);
    }
  },

  // 显示蓝牙连接提示
  showBluetoothTip() {
    wx.showModal({
      title: '蓝牙设备连接提示',
      content: '为了获得更好的音乐治疗体验，请确保您的设备已连接蓝牙治疗仪。请进入手机系统设置，选择并连接蓝牙设备。',
      showCancel: true,
      cancelText: '稍后连接',
      confirmText: '知道了',
      success: (res) => {
        // if (res.confirm) {
        //   // 引导用户去连接蓝牙设备
        //   this.navigateToBluetoothSettings();
        // }
      }
    });
  },

  // 引导用户去连接蓝牙设备
  navigateToBluetoothSettings() {
    // 尝试打开蓝牙设置页面
    wx.openSetting({
      success: (res) => {
        console.log('打开设置页面成功', res);
        if (res.authSetting['scope.bluetooth']) {
          wx.showToast({
            title: '蓝牙权限已开启',
            icon: 'success'
          });
        }
      },
      fail: (error) => {
        console.error('打开设置页面失败', error);
        // 如果无法直接打开设置，提示用户手动操作
        wx.showModal({
          title: '提示',
          content: '请手动进入手机设置，找到蓝牙选项并连接治疗仪设备。',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
  },

  onShow() {
    // 页面显示时检查是否有正在播放的音乐
    console.log('音乐页面显示');
        this.loadMusicFiles();

  },

  onHide() {
    // 页面隐藏时保持背景音频播放
    console.log('音乐页面隐藏，背景音频继续播放');
  },

  onUnload() {
    // 页面卸载时停止背景音频
    if (this.backgroundAudioManager) {
      this.backgroundAudioManager.stop();
    }
  },

  // 从服务器加载音乐文件
  async loadMusicFiles() {
    this.setData({ loading: true });
    try {
      const api = require('../../utils/api.js');
      const response = await api.getMusicFiles({ page: 1, pageSize: 100 });
      
      // 将服务器返回的音乐文件转换为菜单结构
      const musicMenus = this.convertMusicFilesToMenus(response.files);
      this.setData({ musicMenus });
    } catch (error) {
      console.error('加载音乐文件失败:', error);
      wx.showToast({
        title: '加载音乐失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 将音乐文件转换为菜单结构
  convertMusicFilesToMenus(files) {
    // 按分类和播放列表分组
    const categories = {};
    
    files.forEach(file => {
      const category = file.category || '未分类';
      const playlist = file.playlist_name || '默认播放列表';
      
      if (!categories[category]) {
        categories[category] = {
          id: category,
          name: category,
          type: 'category',
          children: {}
        };
      }
      
      if (!categories[category].children[playlist]) {
        categories[category].children[playlist] = {
          id: `${category}-${playlist}`,
          name: playlist,
          type: 'playlist',
          songs: []
        };
      }
      
      // 添加持续时间信息
      const duration = file.duration ? this.formatTime(file.duration) : '00:00';
      
      categories[category].children[playlist].songs.push({
        id: file.id,
        title: file.filename,
        duration: duration,
        url: file.oss_url
      });
    });
    
    // 转换为数组结构
    const musicMenus = Object.values(categories).map(category => {
      return {
        ...category,
        children: Object.values(category.children)
      };
    });
    
    return musicMenus;
  },

  // 加载用户自定义歌单
  loadCustomPlaylists() {
    try {
      const playlists = wx.getStorageSync('customMusicPlaylists') || [];
      this.setData({ customPlaylists: playlists });
    } catch (error) {
      console.error('加载自定义歌单失败:', error);
    }
  },

  // 播放单个歌曲
  playSingleSong(e) {
    const song = e.currentTarget.dataset.song;
    const playlist = e.currentTarget.dataset.playlist;
    
    // 使用背景音频管理器播放音乐
    this.backgroundAudioManager.title = song.title;
    this.backgroundAudioManager.epname = playlist.name;
    this.backgroundAudioManager.singer = '身心放松';
    this.backgroundAudioManager.coverImgUrl = '/images/music.png';
    this.backgroundAudioManager.src = song.url;
    
    this.setData({
      currentPlaying: {
        song: song,
        playlist: playlist
      },
      isPlaying: true,
      currentTime: 0,
      totalTime: this.parseDuration(song.duration)
    });
    
    // 保存当前播放信息到全局
    const app = getApp();
    app.globalData.currentMusic = {
      song: song,
      playlist: playlist
    };
    
    wx.showToast({
      title: `正在播放: ${song.title}`,
      icon: 'none'
    });
  },

  // 选择播放列表（保留原有功能）
  selectPlaylist(e) {
    const playlist = e.currentTarget.dataset.playlist;
    // 播放列表中的第一首歌曲
    if (playlist.songs && playlist.songs.length > 0) {
      this.playSong(playlist.songs[0], playlist);
      wx.showToast({
        title: `开始播放: ${playlist.name}`,
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '该播放列表为空',
        icon: 'none'
      });
    }
  },

  // 播放歌曲（保留原有功能）
  playSong(song, playlist) {
    
    // 使用背景音频管理器播放音乐
    this.backgroundAudioManager.title = song.title;
    this.backgroundAudioManager.epname = playlist.name;
    this.backgroundAudioManager.singer = '身心放松';
    this.backgroundAudioManager.coverImgUrl = '/images/music.png';
    this.backgroundAudioManager.src = song.url;
    
    this.setData({
      currentPlaying: {
        song: song,
        playlist: playlist
      },
      isPlaying: true,
      currentTime: 0,
      totalTime: this.parseDuration(song.duration)
    });
    
    // 保存当前播放信息到全局
    const app = getApp();
    app.globalData.currentMusic = {
      song: song,
      playlist: playlist
    };
  },

  // 暂停/继续播放
  togglePlay() {
    if (this.data.isPlaying) {
      this.backgroundAudioManager.pause();
    } else {
      if (this.data.currentPlaying) {
        this.backgroundAudioManager.play();
      } else {
        wx.showToast({
          title: '请先选择歌曲',
          icon: 'none'
        });
      }
    }
  },

  // 下一首
  nextSong() {
    if (!this.data.currentPlaying) {
      wx.showToast({
        title: '请先播放歌曲',
        icon: 'none'
      });
      return;
    }
    
    const currentPlaylist = this.data.currentPlaying.playlist;
    const currentSong = this.data.currentPlaying.song;
    
    // 确保播放列表和歌曲存在
    if (!currentPlaylist || !currentPlaylist.songs || currentPlaylist.songs.length === 0) {
      wx.showToast({
        title: '播放列表为空',
        icon: 'none'
      });
      return;
    }
    
    // 找到当前歌曲在列表中的位置
    const currentIndex = currentPlaylist.songs.findIndex(song => song.id === currentSong.id);
    
    // 如果找不到当前歌曲，从第一首开始
    if (currentIndex === -1) {
      this.playSong(currentPlaylist.songs[0], currentPlaylist);
      wx.showToast({
        title: `正在播放: ${currentPlaylist.songs[0].title}`,
        icon: 'none'
      });
      return;
    }
    
    // 计算下一首歌曲的索引
    let nextIndex;
    if (this.data.playMode === 'sequence') {
      nextIndex = (currentIndex + 1) % currentPlaylist.songs.length;
    } else if (this.data.playMode === 'random') {
      nextIndex = Math.floor(Math.random() * currentPlaylist.songs.length);
    } else {
      // 单曲循环
      nextIndex = currentIndex;
    }
    
    // 播放下一首歌曲
    this.playSong(currentPlaylist.songs[nextIndex], currentPlaylist);
    wx.showToast({
      title: `正在播放: ${currentPlaylist.songs[nextIndex].title}`,
      icon: 'none'
    });
  },

  // 上一首
  prevSong() {
    if (!this.data.currentPlaying) {
      wx.showToast({
        title: '请先播放歌曲',
        icon: 'none'
      });
      return;
    }
    
    const currentPlaylist = this.data.currentPlaying.playlist;
    const currentSong = this.data.currentPlaying.song;
    
    // 确保播放列表和歌曲存在
    if (!currentPlaylist || !currentPlaylist.songs || currentPlaylist.songs.length === 0) {
      wx.showToast({
        title: '播放列表为空',
        icon: 'none'
      });
      return;
    }
    
    // 找到当前歌曲在列表中的位置
    const currentIndex = currentPlaylist.songs.findIndex(song => song.id === currentSong.id);
    
    // 如果找不到当前歌曲，从第一首开始
    if (currentIndex === -1) {
      this.playSong(currentPlaylist.songs[0], currentPlaylist);
      wx.showToast({
        title: `正在播放: ${currentPlaylist.songs[0].title}`,
        icon: 'none'
      });
      return;
    }
    
    // 计算上一首歌曲的索引
    let prevIndex;
    if (this.data.playMode === 'sequence') {
      prevIndex = (currentIndex - 1 + currentPlaylist.songs.length) % currentPlaylist.songs.length;
    } else if (this.data.playMode === 'random') {
      prevIndex = Math.floor(Math.random() * currentPlaylist.songs.length);
    } else {
      // 单曲循环
      prevIndex = currentIndex;
    }
    
    // 播放上一首歌曲
    this.playSong(currentPlaylist.songs[prevIndex], currentPlaylist);
    wx.showToast({
      title: `正在播放: ${currentPlaylist.songs[prevIndex].title}`,
      icon: 'none'
    });
  },

  // 切换播放模式
  togglePlayMode() {
    const modes = ['sequence', 'single', 'random'];
    const currentIndex = modes.indexOf(this.data.playMode);
    const nextIndex = (currentIndex + 1) % modes.length;
    
    this.setData({
      playMode: modes[nextIndex]
    });
    
    // 显示提示
    const modeText = {
      'sequence': '列表循环',
      'single': '单曲循环',
      'random': '随机播放'
    };
    
    wx.showToast({
      title: modeText[this.data.playMode],
      icon: 'none'
    });
  },

  // 格式化时间
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  },

  // 解析持续时间字符串为秒数
  parseDuration(durationStr) {
    const parts = durationStr.split(':');
    if (parts.length === 2) {
      return parseInt(parts[0]) * 60 + parseInt(parts[1]);
    }
    return 0;
  },

  // 格式化文件大小为持续时间（简化处理）
  formatDuration(fileSize) {
    // 简化处理：假设每MB约等于1分钟
    const minutes = Math.floor(fileSize / (1024 * 1024));
    const seconds = Math.floor((fileSize % (1024 * 1024)) / (1024 * 1024) * 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  },

  // 创建自定义歌单
  createCustomPlaylist() {
    wx.showModal({
      title: '新建歌单',
      content: '请输入歌单名称',
      editable: true,
      placeholderText: '例如：我的放松音乐',
      success: (res) => {
        if (res.confirm && res.content) {
          const newPlaylist = {
            id: Date.now(),
            name: res.content,
            type: 'custom',
            songs: []
          };
          
          const playlists = [...this.data.customPlaylists, newPlaylist];
          this.setData({ customPlaylists: playlists });
          
          // 保存到本地存储
          try {
            wx.setStorageSync('customMusicPlaylists', playlists);
            wx.showToast({
              title: '歌单创建成功',
              icon: 'success'
            });
          } catch (error) {
            console.error('保存歌单失败:', error);
            wx.showToast({
              title: '创建失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 刷新音乐列表
  refreshMusicList() {
    this.loadMusicFiles();
  }
});